//
//  WMRecordViewController.swift
//  deWaterMarkingProject
//
//  Created by admin on 2025/9/9.
//

import UIKit

class WMRecordViewController: WMBaseViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var nodataLabel: UILabel!
    
    var dataList: [WMRecordModel] = []
    var alertView: KBAlertView = KBAlertView()
    override func viewDidLoad() {
        super.viewDidLoad()
        customNavBar.setTitle("历史记录")
        self.tableView.register(UINib(nibName: "WMRecordTableViewCell", bundle: nil), forCellReuseIdentifier: "WMRecordTableViewCell")
        customNavBar.addRightButton(title: "清除", tintColor:UIColor(valueRGB: UInt(OEMInfo.themeHex), alpha: 1.0), target: self, action: #selector(rightButtonClicked))
    }
    
    @objc private func rightButtonClicked() {
        self.alertView = KBAlertView(title: "", "是否清除历史记录", cancelButtonTitle: "取消", otherButtonTitle: "确定") {
            self.alertView.hideView(isRemove: true)
            AppDatabase.shared.deleteAllRecord()
            self.dataList.removeAll()
            self.tableView.reloadData()
            
        } cancelBlock: {
            self.alertView.hideView(isRemove: true)
        }
        self.alertView.doneButtonTitleColor = UIColor(valueRGB: UInt(OEMInfo.themeHex), alpha: 1.0)
        self.alertView.showView()
    }
    

    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        dataList.removeAll()
        dataList.append(contentsOf: AppDatabase.shared.getAllRecord().reversed())
        tableView.reloadData()
        nodataLabel.isHidden = !dataList.isEmpty
    }

}

extension WMRecordViewController: UITableViewDelegate, UITableViewDataSource {
        
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "WMRecordTableViewCell", for: indexPath) as! WMRecordTableViewCell
        cell.record = dataList[indexPath.row]
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = WMRecordInfoViewController(nibName: "WMRecordInfoViewController", bundle: nil)
        vc.record = dataList[indexPath.item]
        navigationController?.pushViewController(vc, animated: true)
    }
    
}

